import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async';

class WebViewPage extends StatefulWidget {
  final String url;
  WebViewPage({Key key, @required this.url}) : super(key: key);
  @override
  _WebViewPageState createState() =>
      _WebViewPageState.withURL(url: url, title: url);
}

class _WebViewPageState extends State<WebViewPage> {
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();
  var url;
  var title;
  var lineProgress;
  bool isLoading = true; // 设置状态
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        actions: <Widget>[
          NavigationControls(_controller.future, title),
        ],
      ),
      body: Center(
        child: Stack(
          children: [
            WebView(
              javascriptMode: JavascriptMode.unrestricted,
              initialUrl: url,
              gestureNavigationEnabled: true,
              onWebViewCreated: (WebViewController webViewController) {
                _controller.complete(webViewController);
              },
              onPageFinished: (String url) {
                setState(() {
                  isLoading = false; // 页面加载完成，更新状态
                });
              },
              navigationDelegate: (NavigationRequest request) {
                setState(() {
                  this.title = request.url;
                  isLoading = true; // 开始访问页面，更新状态
                });
                return NavigationDecision.navigate;
              },
            ),
            isLoading
                ? Container(
                    child: Center(
                      child: CircularProgressIndicator(),
                    ),
                  )
                : Container(),
          ],
        ),
      ),
    );
    // WillPopScope(
    // child:
    // onWillPop: () {
    //   _controller.canGoBack().then((value) {
    //     if (value) {
    //       _controller.goBack();
    //     } else {
    //       return Navigator.pop(context);
    //     }
    //   });
    //   return new Future.value(false);
    // }
    // );
  }

  _WebViewPageState.withURL({@required this.url, String title})
      : this.title = title ?? url;
}

//_progressBar(double progress, BuildContext context) {
//  return LinearProgressIndicator(
//    backgroundColor: Colors.white70.withOpacity(0),
//    value: progress == 1.0 ? 0 : progress,
//    valueColor: new AlwaysStoppedAnimation<Color>(Colors.blue),
//  );
//}

class NavigationControls extends StatelessWidget {
  const NavigationControls(this._webViewControllerFuture,this.url)
      : assert(_webViewControllerFuture != null);
  final Future<WebViewController> _webViewControllerFuture;
  final url;
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<WebViewController>(
      future: _webViewControllerFuture,
      builder:
          (BuildContext context, AsyncSnapshot<WebViewController> snapshot) {
        final bool webViewReady =
            snapshot.connectionState == ConnectionState.done;
        final WebViewController controller = snapshot.data;
        return Row(
          children: <Widget>[
            IconButton(
              icon: const Icon(Icons.arrow_back_ios),
              onPressed: !webViewReady
                  ? null
                  : () async {
                      if (await controller.canGoBack()) {
                        await controller.goBack();
                      } else {
                        Scaffold.of(context).showSnackBar(
                          const SnackBar(content: Text("No back history item")),
                        );
                        return;
                      }
                    },
            ),
            IconButton(
              icon: const Icon(Icons.arrow_forward_ios),
              onPressed: !webViewReady
                  ? null
                  : () async {
                      if (await controller.canGoForward()) {
                        await controller.goForward();
                      } else {
                        Scaffold.of(context).showSnackBar(
                          const SnackBar(
                              content: Text("No forward history item")),
                        );
                        return;
                      }
                    },
            ),
            IconButton(
              icon: const Icon(Icons.replay),
              onPressed: !webViewReady
                  ? null
                  : () {
                      controller.loadUrl(this.url);
                    },
            ),
          ],
        );
      },
    );
  }
}
